﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;

namespace Helper
{
    /// <summary>
    /// file helper
    /// </summary>
    public static class FileHelper
    {
        /// <summary>
        /// export a data table to a excel file
        /// </summary>
        /// <param name="dt">data table</param>
        /// <param name="fileFullName">file full name</param>
        /// <param name="columnMapping">column mapping</param>
        /// <returns>retur true if success, else return false</returns>
        public static bool ExportToExcel(DataTable dt, string fileFullName, Dictionary<string, string> columnMapping)
        {
            if (string.IsNullOrEmpty(fileFullName))
            {
                throw new ArgumentNullException("fileFullName", "file full name is required");
            }
            if (dt == null)
            {
                throw new Exception("There are not data should be exported");
            }

            if (columnMapping == null || columnMapping.Count < 1)
            {
                throw new Exception("There are not column should be exported");
            }

            string exportFileFullName = Path.GetFullPath(fileFullName);

            string folder = Path.GetDirectoryName(exportFileFullName);
            string fileName = Path.GetFileName(exportFileFullName);
            string rootPath = Path.GetPathRoot(exportFileFullName);
            if (folder != rootPath)
            {
                if (Directory.Exists(folder) == false)
                {
                    Directory.CreateDirectory(folder);
                }
            }

            StringBuilder ExcelHTML = new StringBuilder();
            StringBuilder ExcelContent = new StringBuilder();

            ExcelHTML.Append("<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"  xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">");
            ExcelHTML.Append("<head></head>");
            ExcelHTML.Append("<body>\n");

            ExcelHTML.Append("<table >\n");

            #region Add Title
            ExcelContent.Append("<tr>\n");
            foreach (string key in columnMapping.Keys)
            {
                ExcelContent.Append("<td>\n");
                ExcelContent.Append(columnMapping[key]);
                ExcelContent.Append("</td>\n");
            }
            ExcelContent.Append("</tr>\n");
            #endregion

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ExcelContent.Append("<tr>\n");
                foreach (string column in columnMapping.Keys)
                {
                    if (dt.Columns[column].DataType == Type.GetType("System.String"))
                    {
                        ExcelContent.Append("<td x:str type=string>\n");
                    }
                    else
                    {
                        ExcelContent.Append("<td>\n");
                    }

                    if (dt.Rows[i][column] != null)
                    {
                        ExcelContent.Append(dt.Rows[i][column].ToString());
                    }
                    else
                    {
                        ExcelContent.Append(string.Empty);
                    }
                    ExcelContent.Append("</td>\n");
                }
                ExcelContent.Append("</tr>\n");
            }

            ExcelHTML.Append(ExcelContent);
            ExcelHTML.Append("</table>\n");



            ExcelHTML.Append("</body>\n");
            ExcelHTML.Append("</html>\n");


            SaveToFile(exportFileFullName, FileMode.Create, ExcelHTML.ToString());

            return true;
        }

        /// <summary>
        /// save string to a text file
        /// </summary>
        /// <param name="fileFullPath">file full path</param>
        /// <param name="fileMode">file mode</param>
        /// <param name="Value">string</param>
        public static void SaveToFile(string fileFullPath, FileMode fileMode, string Value)
        {
            using (FileStream fs = new FileStream(fileFullPath, fileMode, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (StreamWriter fw = new StreamWriter(fs, Encoding.Unicode))
                {
                    fw.Write(Value);
                    fw.Close();
                }
                fs.Close();
            }
        }

    }
}
